<template>
  <div>
    <el-select v-model="province" placeholder="选择省份" clearable>
      <el-option v-for="(item, key) in areas" :key="key" :label="key" :value="key" />
    </el-select>

    <el-select :disabled="!province" v-model="city" placeholder="选择城市" clearable>
      <el-option v-for="key in selectedCities" :key="key" :label="key" :value="key" />
    </el-select>

    <el-select :disabled="!city" v-model="area" placeholder="选择地区" clearable>
      <el-option v-for="key in selectedAreas" :key="key" :label="key" :value="key" />
    </el-select>

    <el-select :disabled="!area" v-model="street" placeholder="选择乡镇" clearable @change="changeArea">
      <el-option v-for="item in selectedStreets" :key="item" :label="item" :value="item" />
    </el-select>

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import allStreets from "./pcas.json";
// 带 code 文件太大, 改用无 code 版本
// const allStreets = createRequire('./pcas.json')


const province = ref('')
const city = ref('')
const area = ref('')
const street = ref('')

const areas = ref(allStreets)

// 省份变化时,城市跟随变化
const selectedCities = computed(() => {
  city.value = '' // 清除
  if (province.value === '') {
    return []
  }
  // rs = areas.value[province.value]
  let rs = eval('areas.value.' + province.value)
  rs = Object.keys(rs)
  if (rs.length === 1) {
    city.value = rs[0]
  }
  return rs
})

// 城市变化时,地区跟随变化
const selectedAreas = computed(() => {
  area.value = '' // 清除
  if (city.value === '') {
    return []
  }
  let rs = eval('areas.value.' + province.value + '.' + city.value)
  return Object.keys(rs)
})

// 地区变化时,乡镇/街道跟随变化
const selectedStreets = computed(() => {
  street.value = '' // 清除
  if (area.value === '') {
    return []
  }
  let rs = eval('areas.value.' + province.value + '.' + city.value + '.' + area.value)
  return Object.values(rs)
})

// 返回选择数据给父组件
let emits = defineEmits(['change'])
let changeArea = () => {
  if (street) {
    emits('change', { province: province.value, city: city.value, area: area.value, street: street.value })
  }
}
</script>

<style scoped>
</style>